﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;


namespace WareHose.Application.Paging
{
    /// <summary>
    /// 分页静态方法
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public static class PagingMethod
    {
       public static async Task<Tuple<List<T>, PagingDto<T>>> GetPaginatedDataAsync<T>(
       IQueryable<T> query,
       int pageNumber,
       int pageSize,
       Func<IQueryable<T>, IOrderedQueryable<T>> ?orderBy = null)
        {
            if (pageNumber <= 0) throw new ArgumentOutOfRangeException(nameof(pageNumber), "Page number must be greater than zero.");
            if (pageSize <= 0) throw new ArgumentOutOfRangeException(nameof(pageSize), "Page size must be greater than zero.");

            var totalItems = await query.CountAsync();
            var totalPages = (int)Math.Ceiling((double)totalItems / pageSize);

            if (pageNumber > totalPages)
            {
                pageNumber = totalPages;
            }

            var skip = (pageNumber - 1) * pageSize;

            var data = query;
            if (orderBy != null)
            {
                data = orderBy(data);
            }

            var paginatedData = await data
                .Skip(skip)
                .Take(pageSize)
                .ToListAsync();

            var pagingInfo = new PagingDto<T>
            {
              
                TotalRows = totalItems,
                TotalPage = totalPages,
              
            };

            return Tuple.Create(paginatedData, pagingInfo);
        }
    }
}

